package com.littlebee.storysuper.activity;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.bumptech.glide.Glide;
import com.littlebee.storysuper.R;
import com.littlebee.storysuper.entry.EnglistInfoEntry;
import com.littlebee.storysuper.entry.EnglistListEntry;
import com.littlebee.storysuper.entry.User;
import com.littlebee.storysuper.utils.DateUtils;
import com.littlebee.storysuper.utils.GsonUtils;
import com.littlebee.storysuper.utils.LogUtil;
import com.littlebee.storysuper.utils.MyVideoView;
import com.littlebee.storysuper.utils.NetWorkUtils;
import com.littlebee.storysuper.utils.ToastUtil;
import com.littlebee.storysuper.utils.Utils;
import com.littlebee.storysuper.view.CustomDatePickerDialog;
import com.littlebee.storysuper.widget.CircleImageView;
import com.zss.library.activity.BaseActivity;
import com.zss.library.adapter.CommonAdapter;
import com.zss.library.adapter.ViewHolder;
import com.zss.library.toolbar.CommonToolbar;
import com.zss.library.utils.LogUtils;
import com.zss.library.widget.CommonProgressDialog;

import org.json.JSONObject;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/***
 * 英语详情页
 *
 */
public class EnglishInfoActivity extends BaseActivity implements View.OnClickListener {
    private ListView gridView;
    private CommonAdapter<EnglistInfoEntry> mAdapter;
    List<EnglistInfoEntry> names = new ArrayList<EnglistInfoEntry>();
    EnglistListEntry entrys;
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    //获取日期格式器对象
    Calendar calendar = Calendar.getInstance(Locale.CHINA);
    String dateStr = "";
    private boolean fullscreen = false;//全屏/窗口播放切换标志


    /**
     * 是否在播放
     */
    private boolean isPlaying;
    /**
     * 播放进度
     */
    private int currPost = 0;
    /**
     * 用于做延迟加载
     */
    private Handler handler = null;
    /**
     * 视频播放组件
     */
    private VideoView videoView;
    /**
     * 播放or暂停
     */
    private ImageView playPauseIv;
    /**
     * 播放进度
     */
    private TextView nowProgressTv;
    /**
     * 播放进度条
     */
    private SeekBar progressBar;
    /**
     * 总进度
     */
    private TextView totalLengthTv;
    private int diversityIndex = 0;

    /**
     * 播放以前的初始化图片
     */
    private ImageView videoInitIv;
    /**
     * 视频标题
     */
    private TextView videoTitleTv;
    View hand;
    private TextView quanpinTv;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_english_info;
    }

    @Override
    public void initView() {
        super.initView();
        entrys = (EnglistListEntry) getIntent().getSerializableExtra("info");
        gridView = (ListView) findViewById(R.id.listView);

        handler = new Handler();
        hand=getLayoutInflater(R.layout.layout_englist_info_top1);
//        videoInitIv = (ImageView) hand.findViewById(R.id.init_video_iv);
//        videoTitleTv = (TextView) hand.findViewById(R.id.video_title_tv);
//
//        videoView = (VideoView) hand.findViewById(R.id.video_view);
//        playPauseIv = (ImageView) hand.findViewById(R.id.play_pause_iv);
//        nowProgressTv = (TextView) hand.findViewById(R.id.now_progress_tv);
//        progressBar = (SeekBar) hand.findViewById(R.id.progressBar);
//        totalLengthTv = (TextView) hand.findViewById(R.id.total_length_tv);
//        quanpinTv=(TextView)hand.findViewById(R.id.quanp_tv);
//        playPauseIv.setOnClickListener(this);
//        quanpinTv.setOnClickListener(this);
//        quanpinTv.setVisibility(View.VISIBLE);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        getInfo();
        mAdapter = new CommonAdapter<EnglistInfoEntry>(getActivity(), R.layout.layout_item_english) {
            @Override
            protected void convert(ViewHolder viewHolder, final EnglistInfoEntry workerListEntry, final int i) {
                TextView name = viewHolder.findViewById(R.id.tv);
                TextView name1 = viewHolder.findViewById(R.id.tv1);
                TextView name2 = viewHolder.findViewById(R.id.tv2);
                TextView number = viewHolder.findViewById(R.id.number_tv);
                TextView send = viewHolder.findViewById(R.id.send_tv);
                name.setText(workerListEntry.getCartoonname());
                name1.setText(DateUtils.getTimeString((Long.parseLong(workerListEntry.getCartoonduration().trim())) * 1000));
                name2.setText("播放量："+workerListEntry.getCartoonhotpoint());
                number.setText("" + workerListEntry.getCartoonstageno());
                send.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        toSumbit(i);
                    }
                });
            }
        };
        gridView.setAdapter(mAdapter);
        mAdapter.addAll(names);

        // TODO: 2017/8/25 listview顶部会新增东西 具体什么还不清楚 先放个view到这里
        //gridView.addHeaderView(hand);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent(EnglishInfoActivity.this,PlayerInfoActivity.class);
                intent.putExtra("url",names.get(position).getCartoonplayurl());
                intent.putExtra("title",names.get(position).getCartoonname());
                intent.putExtra("pos",0);
                intent.putExtra("pic",entrys.getCartoonseriesminiphotourl());
                startActivity(intent);
            }
        });


    }

    /**
     * 发送给宝宝端
     */
    private void toSumbit(int index) {
        User user = Utils.getUserEntry();
        Map<String, String> map = new HashMap<>();
        map.put("phoneId", user.getMobile());
        map.put("cartoonid", names.get(index).getCartoonid());
        upTime(map,"设置故事播放日期");
    }

    /***
     * 获取列表
     */
    private void getInfo() {

        User user = Utils.getUserEntry();
        Map<String, String> map = new HashMap<>();
        map.put("phoneId", user.getMobile());
        map.put("cartoonseriesid", entrys.getCartoonseriesid());
        // TODO: 2017/8/15
        NetWorkUtils.post(EnglishInfoActivity.this, "getenglishcatoonseriesinfo", map, true, new NetWorkUtils.IListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
                String res = resObj.optString("response")/**.optString("storypages")*/;
                names = GsonUtils.getListFromJSON(res, EnglistInfoEntry.class);
                mAdapter.replaceAll(names);
                if (names != null && names.size() > 0) {
                    videoTitleTv.setText(names.get(diversityIndex).getCartoonname());
                }
                Glide.with(EnglishInfoActivity.this).load(entrys.getCartoonseriesminiphotourl()).error(R.mipmap.logo_img).into(videoInitIv);
            }

            @Override
            public void onError(String result, String code, String msg) {
                LogUtils.i("XHX", "XHXERROR:" + result);
            }
        });

    }

    /**
     * 时间选择器
     */
    private void upTime(final Map<String, String> map,String title) {
        //生成一个DatePickerDialog对象，并显示。显示的DatePickerDialog控件可以选择年月日，并设置
//        DatePickerDialog datePickerDialog = new DatePickerDialog(EnglishInfoActivity.this, new DatePickerDialog.OnDateSetListener() {
//            @Override
//            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
//                //修改日历控件的年，月，日
//                //这里的year,monthOfYear,dayOfMonth的值与DatePickerDialog控件设置的最新值一致
//                calendar.set(Calendar.YEAR, year);
//                calendar.set(Calendar.MONTH, month);
//                calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
//                updateTimeShow(map);
//            }
//
//        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
//        datePickerDialog.setTitle(title);
//        datePickerDialog.show();
        CustomDatePickerDialog dialog = new CustomDatePickerDialog(EnglishInfoActivity.this, Calendar.getInstance(),title);
        dialog.addDateListener(new CustomDatePickerDialog.onDateListener() {

            @Override
            public void dateFinish(Calendar c) {
                //String name=c.get(Calendar.YEAR)+"-"+(c.get(Calendar.MONTH)+1)+"-"+c.get(Calendar.DAY_OF_MONTH);
               updateTimeShow(map,c);

            }
        });

        dialog.show();
    }

    /**
     * 提交
     */
    private void updateTimeShow(Map<String, String> map,Calendar calendar) {
        dateStr = df.format(calendar.getTime());
        map.put("playdate", dateStr);
        LogUtils.i("XHX","XHX时间："+dateStr);
        // TODO: 2017/8/15
        NetWorkUtils.post(EnglishInfoActivity.this, "sendcartoontobaby", map, true, new NetWorkUtils.IListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
                //String res = resObj.optString("response")/**.optString("storypages")*/;
                ToastUtil.displayShortToast("发送成功");
            }

            @Override
            public void onError(String result, String code, String msg) {
            }
        });
    }

    private void initPlayer(int diversityIndex, int currPost) {
        videoInitIv.setVisibility(View.GONE);
        videoTitleTv.setVisibility(View.GONE);

        playPauseIv.setImageResource(R.mipmap.ransfer_media_pause);

        videoTitleTv.setText(names.get(diversityIndex).getCartoonname());
        play(names.get(diversityIndex).getCartoonplayurl(), currPost);
    }

    private SeekBar.OnSeekBarChangeListener change = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // 当进度条停止修改的时候触发
            // 取得当前进度条的刻度
            int progress = seekBar.getProgress();
            if (videoView != null && videoView.isPlaying()) {
                // 设置当前播放的位置
                videoView.seekTo(progress);
                //修改时间
            }
        }
    };

    /**
     * 播放咯
     *
     * @param path 地址
     * @param msec 播放进度
     */
    protected void play(String path, int msec) throws NullPointerException {
        //获取视频文件地址

        videoView.setVideoURI(Uri.parse(path));
        LogUtils.i("XHX", "初始化播放器了");
        //开始播放
        videoView.start();

        // 按照初始位置播放
        videoView.seekTo(msec);

        //修改时间
        // 开始线程，更新进度条的刻度
        new Thread() {
            @Override
            public void run() {
                try {
                    isPlaying = true;
                    while (isPlaying) {
                        // 如果正在播放，没0.5.毫秒更新一次进度条
                        int current = videoView.getCurrentPosition();
                        progressBar.setMax(videoView.getDuration());
                        progressBar.setProgress(current);
                        handler.post(runnableUi);
                        sleep(1000);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
        videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {

            @Override
            public void onCompletion(MediaPlayer mp) {
                // 在播放完毕被回调 续播还是结束播放
                if (diversityIndex < names.size() - 1) {
                    diversityIndex += 1;
                    currPost = 0;
                    videoTitleTv.setText(names.get(diversityIndex).getCartoonname());
                    play(names.get(diversityIndex).getCartoonplayurl(), currPost);
                } else {
                    videoInitIv.setVisibility(View.VISIBLE);
                    videoTitleTv.setVisibility(View.VISIBLE);
                    ToastUtil.displayShortToast("播放结束");

                }
            }
        });

        videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {

            @Override
            public boolean onError(MediaPlayer mp, int what, int extra) {
                //TODO  发生错误重新播放
                play(names.get(diversityIndex).getCartoonplayurl(), 0);
                isPlaying = false;
                return false;
            }
        });
    }

    // 构建Runnable对象，在runnable中更新界面
    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            //更新界面播放进度的文字标识
            if (videoView.getDuration() != -1) {
                totalLengthTv.setText(DateUtils.getTimeString(videoView.getDuration()));
            }
            nowProgressTv.setText(DateUtils.getTimeString(videoView.getCurrentPosition()));

        }

    };

    @Override
    public void setTopBar() {
        super.setTopBar();
        setStatusBarColor(R.color.module_video_bg);
        CommonToolbar toolbar = getToolbar();
        toolbar.setBgRes(R.color.module_video_bg);
        toolbar.setTitle(entrys.getCatoonseriesname());

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.play_pause_iv:
                if (videoView != null && videoView.isPlaying()) {
                    playPauseIv.setImageResource(R.mipmap.ransfer_media_play);
                    currPost = videoView.getCurrentPosition();
                    videoView.pause();
                    isPlaying = false;
                } else {

                    playPauseIv.setImageResource(R.mipmap.ransfer_media_pause);
                    videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            videoInitIv.setVisibility(View.GONE);
                            videoTitleTv.setVisibility(View.GONE);
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    mHandler.sendEmptyMessageDelayed(1, 0);
                                }
                            }).start();
                        }
                    });
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            mHandler.sendEmptyMessageDelayed(0, 0);
                        }
                    }).start();
                    play(names.get(diversityIndex).getCartoonplayurl(), currPost);
                }
                break;
            case R.id.quanp_tv:
//                fullscreen=!fullscreen;
//                changVideo();
                Intent intent=new Intent(this,PlayerInfoActivity.class);
                intent.putExtra("url",names.get(diversityIndex).getCartoonplayurl());
                intent.putExtra("title",names.get(diversityIndex).getCartoonname());
                intent.putExtra("pos",videoView.getCurrentPosition());
                startActivity(intent);
                break;
        }
    }

    private static CommonProgressDialog dialog;

    public static void showProgressDialog(Context mContext, final String showStr) {
        if (mContext != null) {
            if (dialog == null) {
                dialog = new CommonProgressDialog(mContext);
                dialog.setTitle(showStr);
                dialog.setCancelable(true);
                dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface d, int keyCode, KeyEvent event) {
                        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                            dialog.dismiss();
                            dialog = null;
                        }
                        return false;
                    }
                });
                dialog.show();
            } else {
                if (!dialog.isShowing()) {
                    dialog.show();
                }
            }
        }
    }

    public static void dismissProgressDialog(Context mContext) {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    showProgressDialog(EnglishInfoActivity.this, "正在缓冲……");
                    break;
                case 1:
                    dismissProgressDialog(EnglishInfoActivity.this);
                    break;

            }
        }

    };

}
